package com.leyou.gateway.filter;

import com.leyou.auth.inter.pojo.UserInfo;
import com.leyou.auth.inter.util.JwtUtils;
import com.leyou.auth.inter.util.TokenState;
import com.leyou.common.bean.Constant;
import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.CookieUtils;
import com.leyou.common.util.StringUtil;
import com.leyou.common.util.UrlUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.util.AuthUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zqq
 * @ClassName LoginFilter
 * @Description
 * @date 2020/3/10-9:15
 */
@Component
@Slf4j
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties properties;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest req = ctx.getRequest();
        // 获取路径
        String requestURI = req.getRequestURI();
        // 判断白名单
        Boolean bool = UrlUtils.check(this.filterProp.getAllowPaths(),requestURI);
        return !bool;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        // 获取token
        String token = request.getHeader("x-authorize-token");
        if(!StringUtil.isEmpty(token)){
            log.info("非法访问，未登录");
            AuthUtils.response(context,ResultCode.S_SYSTEM_VISIT_EXCEPTION);
            return null;
        }
        UserInfo userInfo = null;
        Map<String, Object> map = JwtUtils.validParseJWT(token, this.properties.getPublicKey());
        switch ((TokenState)map.get("state")){
            case VALID:
                userInfo = (UserInfo) map.get("userInfo");
                String key = Constant.KEY_TOKEN_ID+userInfo.getId();
                String cacheToken = this.redisTemplate.opsForValue().get(key);
                if(!StringUtil.isEmpty(cacheToken)){
                    log.info("token已过期");
                    AuthUtils.response(context,ResultCode.V_TOKEN_EXP);
                    return null;
                }
                //防止一直持有过期Token访问
                if(!token.equals(cacheToken)){
                    log.info("token已过期");
                    AuthUtils.response(context,ResultCode.V_TOKEN_EXP);
                    return null;
                }
                break;
            case EXPIRED:
                log.info("token已过期");
                AuthUtils.response(context,ResultCode.V_TOKEN_EXP);
                return null;
            case SIGNATURE:
                log.info("token签名异常");
                AuthUtils.response(context,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return null;
            case ISS_EXCEPTION:
                log.info("token签发者异常");
                AuthUtils.response(context,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return null;
            case ANALYSIS_EXCEPTION:
                log.info("token解析异常");
                AuthUtils.response(context,ResultCode.V_TOKEN_UNAUTHORIZED_FAIL);
                return null;
            default:
                break;
        }
        //权限判断
        boolean bool = AuthUtils.checkAuthorize(request, redisTemplate, userInfo);
        if(!bool){
            log.info("请求失败，无权访问");
            AuthUtils.response(context,ResultCode.V_NOT_AUTHORIZE_ERROR);
            return null;
        }
        return null;
    }

}
